//
//  LoginViewController.m
//  AddressBook
//
//  Created by 解晓东 on 15/11/7.
//  Copyright (c) 2015年 sasa. All rights reserved.
//

#import "LoginViewController.h"
#import "MBProgressHUD+MJ.h"

#define USERNAMEKEY @"name"
#define PWDKEY @"pwd"
#define RMBPWDKEY @"rmb_pwd"

@interface LoginViewController ()

@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (weak, nonatomic) IBOutlet UITextField *pwdField;
@property (weak, nonatomic) IBOutlet UISwitch *rembSwitch;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

- (IBAction)loginAction;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 添加观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.nameField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.pwdField];

    // 读取上次的配置
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    self.nameField.text = [defaults valueForKey:USERNAMEKEY];
    self.pwdField.text = [defaults valueForKey:PWDKEY];
    self.rembSwitch.on = [defaults boolForKey:RMBPWDKEY];
    if (self.rembSwitch.isOn) {
        self.pwdField.text = [defaults valueForKey:PWDKEY];
        self.loginBtn.enabled = YES;
    }
}

#pragma mark - 修改按钮的状态
- (void)textChange {
    // 用户名和密码都不为空，按钮才能点击
    /*
    if (self.nameField.text.length && self.pwdField.text.length) {
        self.loginBtn.enabled = YES;
    } else {
        self.loginBtn.enabled = NO;
    }
     */
    
    self.loginBtn.enabled = (self.nameField.text.length && self.pwdField.text.length);
}

#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // 1.取得目标控制器
    UIViewController *contactVc = segue.destinationViewController;
    // 2.设置标题（传值）
    contactVc.title = [NSString stringWithFormat:@"%@的联系人列表", self.nameField.text];
}

#pragma mark - 登陆
- (IBAction)loginAction {
    if (![self.nameField.text isEqualToString:@"admin"]) {
        [MBProgressHUD showError:@"账号不存在！"];
        return;
    }
    if (![self.pwdField.text isEqualToString:@"admin"]) {
        [MBProgressHUD showError:@"密码错误！"];
        return;
    }
    // 显示蒙版（遮盖）
    [MBProgressHUD showMessage:@"努力加载中..."];
    // 模拟2秒跳转，以后要发送网络请求
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 移除遮盖
        [MBProgressHUD hideHUD];
        // 跳转到联系人列表界面
        [self performSegueWithIdentifier:@"LoginToContact" sender:nil];
    });
    
    // 存储数据
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.nameField.text forKey:USERNAMEKEY];
    [defaults setObject:self.pwdField.text forKey:PWDKEY];
    [defaults setBool:self.rembSwitch.isOn forKey:RMBPWDKEY];
    // 设置同步
    [defaults synchronize];
}

@end
